<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router';
import { useTokenStore } from '../../stores/token'
import {
  getByIdAssService,
  addStudentAssService,
  updateStudentAssService,
} from '../../api/studentAss'
import { getStudentByIdService } from '../../api/student'
import { getByIdAssignmentService } from '../../api/assignment'

const route = useRoute();
const searchQuery = ref('') // 新增的搜索条件
const studentAsss = ref([]);
// 弹框标题
const title = ref('')
const imageUrl = ref('');
const assignmentTitle = ref(''); // 或者通过其他逻辑获取作业名称
//控制添加学生作业弹窗
const dialogVisible = ref(false)
const imgTableVisible = ref(false)
const fileName = ref(''); // 新增：用于存储文件名
// 学生作业表单模型
const studentAssModel = ref({
  title: '',
  info: '',
  id: 0,
})

// 新增：分页相关变量
const currentPage = ref(1); // 当前页码
const pageSize = ref(5); // 每页显示条目数
const totalItems = ref(0); // 总条目数

// 新增：存储选中的行
const selectedRows = ref([]);

const filteredNotices = computed(() => {
  return studentAsss.value.filter(studentAss =>
    studentAss.info.includes(searchQuery.value)
  ).slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
});

// 显示学生作业列表信息
const studentAssList = async () => {
  const assignmentId = computed(() => route.query.assId); // 获取 assignmentId
  let assId = assignmentId.value;
  let res = await getByIdAssService(assId)
  const studentAsssData = res.data;
  const Promises = studentAsssData.map(async (studentAss) => {
    const assignmentResponse = await getByIdAssignmentService(studentAss.assId);
    const studentResponse = await getStudentByIdService(studentAss.stuId);
    assignmentTitle.value = assignmentResponse.data.title; // 添加作业名字
    studentAss.student = studentResponse.data.name; // 添加学生名字
    return studentAss;
  });
  studentAsss.value = await Promise.all(Promises); // 等待所有请求完成
  totalItems.value = studentAsss.value.length; // 更新总条目数
};

// 处理分页变化
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};

// 批量下载所选文件
const batchDownloadFiles = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先选择要下载的文件');
    return;
  }

  selectedRows.value.forEach(row => downloadFile(row));
};

import * as XLSX from 'xlsx';
const handleImageError = () => {
  // 当图片加载失败时，将 imageUrl 设置为空字符串
  imageUrl.value = '';
};
// 导出成绩
const exportFile = () => {
  // 获取需要导出的数据
  const dataToExport = filteredNotices.value.map(studentAss => ({
    作业名: studentAss.title,
    学生名: studentAss.student,
    附加内容: studentAss.info,
    成绩: studentAss.score,
  }));

  // 创建工作簿
  const worksheet = XLSX.utils.json_to_sheet(dataToExport);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '学生作业成绩');

  // 导出 Excel 文件
  XLSX.writeFile(workbook, '学生作业成绩.xlsx');
};

const addNotice = async () => {
  let res = await addStudentAssService(studentAssModel.value)
  if (res) {
    ElMessage.success(res.message ? res.message : '添加成功')
    studentAssList()
    dialogVisible.value = false
  } else {
    ElMessage.error(res.message ? res.message : '很可惜，添加失败了')
  }
}

// 修改是弹窗展示编辑原信息
const showNotice = (row) => {
  // 放在组件里不需要.value ,放在scrpit体内就要
  dialogVisible.value = true
  title.value = '修改学生作业'
  studentAssModel.value.score = row.score
  
}
// 提取文件名和后缀
const extractFileName = (fileLink) => {
  const url = new URL('/api' + fileLink, window.location.origin);
  const params = new URLSearchParams(url.search);
  return params.get('fileName') || '未知文件名';
};
//编辑学生作业
const editNotice = async () => {
  let res = await updateStudentAssService(studentAssModel.value)
  ElMessage.success(res.message ? res.message : '修改成功!')
  studentAssList()
  dialogVisible.value = false
}

//查看作业
const showAssignment = async(file) => {
  imgTableVisible.value=true
  // 如果有文件链接，尝试获取图片并设置到 imageUrl
  if (file) {
    try {
      const response = await fetch('/api' + file, {
        headers: {
          Authorization: `${useTokenStore().token}`,
        },
      });
      if (!response.ok) throw new Error('Network response was not ok');
      const blob = await response.blob();
      imageUrl.value = URL.createObjectURL(blob);
      fileName.value = extractFileName(file); // 设置文件名
    } catch (error) {
      console.error('Failed to load image:', error);
      imageUrl.value = ''; 
    }
  } else {
    imageUrl.value = ''; // 没有文件时清除 imageUrl
  }
}
// 下载
const downloadFile = (fileLink) => {
  console.log(fileLink.file);
  const fileUrl = fileLink.file;
  fetch('/api' + fileUrl, {
    method: 'GET',
    headers: {
      'Authorization': `${useTokenStore().token}`
    }
  })
  .then(response => {
    if (!response.ok) {  // 检查响应状态
      throw new Error(`下载失败，状态码: ${response.status}`); // 输出失败原因
    }
    return response.blob(); // 将响应转换为 Blob 对象
  })
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = fileUrl.split('/').pop(); // 指定下载的文件名和扩展名
    document.body.appendChild(a);
    a.click(); // 自动点击下载链接
    document.body.removeChild(a); // 下载后移除链接元素
    window.URL.revokeObjectURL(url); // 释放对象 URL
  })
  .catch(error => {
    // 改进的错误处理
    console.error('下载过程中出现问题:', error);
    ElMessage({
      message: '下载失败，请重试。',
      type: 'error',
    });
  });
}
//返回上一页
const goBack = () => {  
  window.history.go(-1)
}

onMounted(() => {
  studentAssList();
});
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <el-page-header @back="goBack">
          <template #content>
            <span>{{ assignmentTitle }}</span>
          </template>
        </el-page-header>
        <el-input 
          v-model="searchQuery" 
          placeholder="搜索相关学生作业..." 
          style="width: 200px; margin-right: 10px;" 
        />
        <div class="extra">
          <el-button @click="exportFile" type="primary">导出成绩</el-button>
          <!-- 新增：批量下载按钮 -->
          <el-button @click="batchDownloadFiles" type="success">批量下载</el-button>
        </div>
      </div>
    </template>

    <!-- 修改成绩 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form :model="studentAssModel" label-width="100px" style="padding-right: 30px">
        <el-form-item label="作业成绩" prop="score">
          <el-input v-model="studentAssModel.score" minlength="1" maxlength="10"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="title == '添加学生作业' ? addNotice() : editNotice()">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 查看作业 -->
    <el-dialog v-model="imgTableVisible" title="查看作业" width="800">
      <el-image 
          v-if="imageUrl"
          style="width: 200px; height: 200px"
          :src="imageUrl" 
          :preview-src-list="[imageUrl]"
          @error="handleImageError"
        >
        </el-image>  
        <p>{{ fileName }}</p>
        <!-- <el-button @click="downloadFile()" type="text">下载查看</el-button> -->
    </el-dialog>
    <!-- 列表 -->
    <el-table 
      :data="filteredNotices" 
      style="width: 100%" 
      @selection-change="val => selectedRows = val"
    >
      <!-- 新增：选择列 -->
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="序号" width="70" type="index"> </el-table-column>
      <el-table-column label="学生" prop="student"></el-table-column>
      <el-table-column label="附加内容" prop="info"></el-table-column>
      <el-table-column label="作业" prop="file">
        <template #default="{ row }">
          <el-button type="success" plain @click="showAssignment(row.file)">查看作业</el-button>
          <el-button @click="downloadFile(row)" type="text">下载查看</el-button>
        </template>
        
      </el-table-column>
      <el-table-column label="成绩" prop="score"></el-table-column>
      <el-table-column label="上传时间" prop="createAt"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showNotice(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 新增：分页组件 -->
    <el-pagination
      layout="prev, pager, next"
      :total="totalItems"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
      style="margin-top: 20px;"
    />
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>